// Shatter Toolkit
// Copyright 2011 Gustav Olsson
using System.Collections.Generic;
using UnityEngine;

public class MouseSaw : MonoBehaviour
{
	public int raycastCount = 5;
	
	private bool started = false;
	public Vector3 start, end;
	
	
	public void Update()
	{
		if (Input.GetMouseButtonDown(0))
		{
			start = Input.mousePosition;
			
			started = true;
		}
		
		if (Input.GetMouseButtonUp(0) && started)
		{
			end = Input.mousePosition;
			
			// Calculate the world-space line
			Camera mainCamera = Camera.main;
			
			float near = mainCamera.nearClipPlane;
			
			Vector3 line = mainCamera.ScreenToWorldPoint(new Vector3(end.x, end.y, near)) - mainCamera.ScreenToWorldPoint(new Vector3(start.x, start.y, near));
			
			
            //lyf add
//			float thirdPointY = 0.0f;
//			if( end.x == start.x )
//			{
//				thirdPointY = end.y;
//			}
//			else 
//			{
//            	float k = -(end.y - start.y) / (end.x - start.x);
//           	 	float b = end.y - k * end.x;
//            	thirdPointY = k * start.x + b;
//			}

            //Vector3 verticalLine = mainCamera.ScreenToWorldPoint(new Vector3(end.x, end.y, near)) - mainCamera.ScreenToWorldPoint(new Vector3(start.x, thirdPointY, near));
			
			// Find game objects to split by raycasting at points along the line
			for (int i = 0; i < raycastCount; i++)
			{
				Ray ray = mainCamera.ScreenPointToRay(Vector3.Lerp(start, end, (float)i / raycastCount));
				
				RaycastHit hit;
				
				if (Physics.Raycast(ray, out hit))
				{
					Plane splitPlane = new Plane(Vector3.Normalize(Vector3.Cross(line, ray.direction)), hit.point);
					
					//Vector3 VerticalNormal = Vector3.Normalize((Vector3.Cross(verticalLine, ray.direction)));
					
//					Vector3 startPos = mainCamera.ScreenToWorldPoint(new Vector3(start.x, start.y, near));
//					Vector3 endPos = mainCamera.ScreenToWorldPoint(new Vector3(end.x, end.y, near));
//					Vector3 spectVect = startPos - endPos;
					
					//float tag = Vector3.Dot( VerticalNormal, line );
					Plane VerticalPlane;
//					if( tag > 0.0f )
//                    	VerticalPlane = new Plane(VerticalNormal, hit.point);
//					else 
//						VerticalPlane = new Plane(-VerticalNormal, hit.point);
					
					line.Normalize();
					VerticalPlane = new Plane( line, hit.point );
						
					//hit.collider.SendMessage("Split", new Plane[] { splitPlane }, SendMessageOptions.DontRequireReceiver);
					hit.collider.SendMessage("Saw", new Plane[] { splitPlane, VerticalPlane}, SendMessageOptions.DontRequireReceiver);
				}
			}
			
			started = false;
		}
	}
}